package com.items.blog.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.items.blog.mapper.BlogInfoMapper;
import com.items.blog.mapper.UserInfoMapper;
import com.items.blog.model.BlogInfo;
import com.items.blog.model.Result;
import com.items.blog.model.UserInfo;
import com.items.blog.utils.JwtUtils;
import com.items.blog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class UserService {
    @Autowired
    MailSender mailSender;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private BlogInfoMapper blogInfoMapper;


    public UserInfo queryByName(String userName) {
        return userInfoMapper.queryByName(userName);
    }

    public UserInfo queryById(Integer userId) {
        return userInfoMapper.queryById(userId);
    }

    public UserInfo getAuthorInfo(Integer blogId) {
        BlogInfo blogInfo = blogInfoMapper.queryById(blogId);
        if (blogInfo == null || blogInfo.getUserId() < 0) {
            return null;
        }
        return userInfoMapper.queryById(blogInfo.getUserId());
    }

    /**
     * 注册账号
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> createAccount(UserInfo userInfo) {
        //雪花算法生成确认码
        String confirmCode = IdUtil.getSnowflake(1, 1).nextIdStr();
        //盐
        String salt = RandomUtil.randomString(6);
        //加密密码：原始密码+盐
        String md5Pwd = SecureUtil.md5(userInfo.getPassword() + salt);
        //激活失效时间：24小时
        LocalDateTime ldt = LocalDateTime.now().plusDays(1);
        // userInfo.setUserName("liudong");
        //初始化用户信息
        userInfo.setSalt(salt);
        userInfo.setPassword(md5Pwd);
        userInfo.setConfirmCode(confirmCode);
        userInfo.setActivationTime(ldt);
        userInfo.setIsValid((byte) 0);
        //新增账号
        int result = userInfoMapper.insertUser(userInfo);
        //初始化map
        Map<String, Object> resultMap = new HashMap<>();
        if (result > 0) {
            //发送邮箱
            String activationUrl = "http://localhost:8080/user/activation?confirmCode=" + confirmCode;
//            mailService.sendMailForActivationAccount(activationUrl,userInfo.getEmail());
            resultMap.put("code", 200);
            resultMap.put("message", "注册成功，请前往邮箱进行账号激活");
        } else {
            resultMap.put("code", 400);
            resultMap.put("message", "注册失败");
        }
        return null;
    }

    /**
     * 激活账号
     */
    @Transactional
    public Map<String, Object> activationAccount(String confirmCode) {
        Map<String, Object> resultMap = new HashMap<>();
        //根据确认码查询用户
        UserInfo userInfo = userInfoMapper.selectUserByConfirmCode(confirmCode);
        //判断激活时间是否超时
        boolean after = LocalDateTime.now().isAfter(userInfo.getActivationTime());
        if (after) {
            resultMap.put("code", 400);
            resultMap.put("message", "链接失效重新注册！");
            return resultMap;
        }
        //根据用户状态码查询用户，并修改状态值为1
        int result = userInfoMapper.updateUserByConfirmCode(confirmCode);
        if (result > 0) {
            resultMap.put("code", 200);
            resultMap.put("message", "激活成功！");
        } else {
            resultMap.put("code", 400);
            resultMap.put("message", "激活失败！");
        }
        return resultMap;

    }
    /**
     *
     * 登录账号
     */
//    public Map<String ,Object> loginAccount(UserInfo userInfo) {
//        Map<String,Object> resultMap = new HashMap<>();
//        //根据邮箱查询用户
//        List<UserInfo> userInfoList =userInfoMapper.selectUserByEmail(userInfo.getEmail());
//        //查询不到结果，返回：该账号不存在或未激活
//        if (userInfoList == null || userInfoList.isEmpty()){
//            resultMap.put("code",400);
//            resultMap.put("message","该账户不存在或未激活");
//            return resultMap;
//        }
//        //查到多个用户，返回：账号异常，请联系管理员
//        if (userInfoList.size() > 1){
//            resultMap.put("code",400);
//            resultMap.put("message","账号异常，请联系管理员");
//            return resultMap;
//        }
//        //查到一个用户，进行密码比较
//        UserInfo u = userInfoList.get(0);
//        //用户输入的密码和盐进行加密
//        String md5Pwd = SecureUtil.md5(userInfo.getPassword()+ u.getSalt());
//        //密码不一致，返回：用户名或密码错误
//        if (!u.getPassword().equals(md5Pwd)){
//            resultMap.put("code",400);
//            resultMap.put("message","用户名或密码错误");
//            return resultMap;
//        }
//        resultMap.put("code",200);
//        resultMap.put("message","登录成功");
//        return resultMap;
//    }

}
